package com.itzhouwei.commerce.advice;

import com.itzhouwei.commerce.annotation.IgnoreResponseAdvice;
import com.itzhouwei.commerce.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.Serializable;

/**
 * 实现统一响应
 * @description: 实现统一响应
 * @author：zw，微信公共号：yingshengzw
 * @date: 2021/8/28
 * @Copyright：公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、学习、分享、成长，让自己和他人都能有所收获！
 */
@RestControllerAdvice(value = "com.itzhouwei.commerce")
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /***
     * 判断是否需要对响应进行处理
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    @SuppressWarnings("all")
    public boolean supports(MethodParameter methodParameter, Class aClass) {

        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }

        if (methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return  false;
        }

        return true;
    }

    @SuppressWarnings("all")
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        //定义最终返回对象
        CommonResponse<Object> response=new CommonResponse<>(0,"");
        if (null==o){
            return response;
        }else if (o instanceof CommonResponse){
            response=(CommonResponse<Object>) o;
        }else{
            response.setData(o);
        }
        return response;
    }



}
